﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Configuration;

namespace WeakEndForum
{
    public partial class NewTopic : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Modules.isUserConnected())
            {
                Server.Transfer("Error401.aspx");
            }
        }

        protected void btnNewTopic_Click(object sender, EventArgs e)
        {
            if (!Modules.isUserConnected())
            {
                Server.Transfer("Error401.aspx");
            }
            else
            {
                string newTopicTitle = txtNewTopicTitle.Text;
                string newTopicContent = txtNewTopicContent.Text;
                string newTopicAuthor = Modules.getConnectedUser();
                OleDbConnection connexion = new OleDbConnection(ConfigurationManager.ConnectionStrings[Constantes.DB_NAME].ConnectionString);
                connexion.Open();
                OleDbCommand postContent = new OleDbCommand("INSERT INTO Sujets (Titre, Auteur) VALUES (@title, @author);", connexion);
                postContent.Parameters.Add(new OleDbParameter("title", newTopicTitle) { OleDbType = OleDbType.VarChar, Size = 255 });
                postContent.Parameters.Add(new OleDbParameter("author", newTopicAuthor) { OleDbType = OleDbType.VarChar, Size = 255 });
                postContent.Prepare();
                postContent.ExecuteNonQuery();
                OleDbCommand getNewPostID = new OleDbCommand("SELECT @@IDENTITY;", connexion);
                int newPostID = (int)getNewPostID.ExecuteScalar();
                OleDbCommand newPostMessage = new OleDbCommand("INSERT INTO Messages (Contenu, Auteur, Sujet) VALUES (@content, @author, @subject)", connexion);
                newPostMessage.Parameters.Add(new OleDbParameter("content", newTopicContent) { OleDbType = OleDbType.LongVarChar, Size = 65535 });
                newPostMessage.Parameters.Add(new OleDbParameter("author", newTopicAuthor) { OleDbType = OleDbType.VarChar, Size = 255 });
                newPostMessage.Parameters.Add(new OleDbParameter("subject", newPostID) { OleDbType = OleDbType.Integer });
                newPostMessage.ExecuteNonQuery();
                connexion.Close();
                Response.Redirect("Topic.aspx?tID=" + newPostID.ToString());
            } 
        }
    }
}